package com.yswee.framework.widget.imageview;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.yswee.framework.utils.LogcatUtils;

public class MSensorImageView extends ImageView {

    private static final String TAG = MSensorImageView.class.getSimpleName();

    private static final int ROTATE_MAX = 35;
    private static final int ROTATE_X_MANU = 30;

    // 用来保存加速度传感器的值
    private float[] mValueGravity = new float[3];
    // 用来保存地磁传感器的值
    private float[] mValueGeomagnetic = new float[3];
    // 用来保存matrix的值
    private float[] mValueR = new float[9];
    //  用来保存最终的结果
    private float[] mValues = new float[3];

    private Matrix mMatrix;
    private Camera mCamera;
    private float mCameraRotateX;
    private float mCameraRotateY;
    private SensorManager mSensorManager;
    private SensorEventListener mSensorEventListener;

    public MSensorImageView(Context context) {
        super(context);
        initializeView(context);
    }

    public MSensorImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initializeView(context);
    }

    public MSensorImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initializeView(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MSensorImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initializeView(context);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (null != mSensorManager && null != mSensorEventListener) {
            Sensor magneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
            Sensor accelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            mSensorManager.registerListener(mSensorEventListener, magneticSensor,
                    SensorManager.SENSOR_DELAY_NORMAL);
            mSensorManager.registerListener(mSensorEventListener, accelerometerSensor,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (null != mSensorManager && null != mSensorEventListener) {
            mSensorManager.unregisterListener(mSensorEventListener);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        applyCameraRotate(canvas);
        super.onDraw(canvas);
    }

    private void initializeView(Context context) {
        mMatrix = new Matrix();
        mCamera = new Camera();
        if (null == mSensorManager) {
            mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
        }
        if (null == mSensorEventListener) {
            mSensorEventListener = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                        mValueGeomagnetic = event.values;
                    }
                    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                        mValueGravity = event.values;
                        setCameraRotate();
                        invalidate();
                    }
                }

                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {

                }
            };
        }
    }

    private void setCameraRotate() {
        SensorManager.getRotationMatrix(mValueR, null, mValueGravity, mValueGeomagnetic);
        SensorManager.getOrientation(mValueR, mValues);
//        double degreeZ = Math.toDegrees(mValues[0]);
        double degreeX = Math.toDegrees(mValues[1]);
        double degreeY = Math.toDegrees(mValues[2]);
        LogcatUtils.e(TAG, "x:" + degreeX + ",y:" + degreeY);
        mCameraRotateX = (float) degreeX + ROTATE_X_MANU;
        mCameraRotateY = (float) degreeY;
        if (mCameraRotateX > ROTATE_MAX) {
            mCameraRotateX = ROTATE_MAX;
        } else if (mCameraRotateX < -ROTATE_MAX) {
            mCameraRotateX = -ROTATE_MAX;
        }
        if (mCameraRotateY > ROTATE_MAX) {
            mCameraRotateY = ROTATE_MAX;
        } else if (mCameraRotateY < -ROTATE_MAX) {
            mCameraRotateY = -ROTATE_MAX;
        }
    }

    private void applyCameraRotate(Canvas canvas) {
        mMatrix.reset();
        mCamera.save();
        mCamera.rotateX(mCameraRotateX);
        mCamera.rotateY(-mCameraRotateY);
        mCamera.getMatrix(mMatrix);
        mCamera.restore();
        /**
         * Camera默认位于视图的左上角，故生成的矩阵默认也是以其左上角为旋转中心，
         * 所以在动作之前调用preTranslate将mMatrix向左移动getWidth()/2个长度，
         * 向上移动getHeight()/2个长度，
         * 使旋转中心位于矩阵的中心位置，动作之后再post回到原位
         */
        mMatrix.preTranslate(-getWidth() / 2, -getHeight() / 2);
        mMatrix.postTranslate(getWidth() / 2, getHeight() / 2);
        canvas.concat(mMatrix);
    }

}